import json
import os
import time
from datetime import datetime, timedelta

import pytz
from fastapi.security import OAuth2PasswordBearer

from api.endpoints.common import write_access_log
# from api.extends.sms import check_code
from core.Response import success, fail, res_antd
from models.models import User, AccessLog, Userposts, Post, Order, User_vip
from schemas import user
from core.Utils import en_password, check_password, random_str, process_payment_request
from core.Auth import create_access_token, check_permissions, decode_access_token
from fastapi import Request, Query, APIRouter, Security, File, UploadFile, Depends, Body
from config import settings
from typing import List
from tortoise.queryset import F

from schemas.posts import detail_id, Order_Pydantic
from schemas.user import UpdateUserInfo, ModifyMobile, LoginUser

router = APIRouter(prefix='')


@router.post('/login')
async def login(request: Request, user_info: LoginUser):
    user_obj = await User.get_or_none(username=user_info.username)
    if user_obj is None:
        return fail(msg='用户名或密码错误')
    if not check_password(user_info.password, user_obj.password):
        return fail(msg='用户名或密码错误')
    access_token = create_access_token({"username": user_obj.username,
                                        "user_email": user_obj.user_email,
                                        "client_host": user_obj.client_host,
                                        'id': user_obj.id,
                                        })
    await write_access_log(request, user_obj.id, '登录成功！')
    user_info_without_excluded_fields = {
        'id': user_obj.id,
        "username": user_obj.username,
        "user_email": user_obj.user_email,
        'bio': user_obj.bio,
        'avatar': user_obj.avatar,
        'level': user_obj.level,
        'integral': user_obj.integral,
    }

    return success(data={'access_token': access_token, 'user_info': user_info_without_excluded_fields})


@router.post('/signin')
async def register(request: Request, user_info: user.CreateUser):
    user_info.dict()['integral_time'] = None

    # 使用 get_or_none 方法确保只返回一个对象
    user_obj = await User.get_or_none(username=user_info.username)
    if user_obj:
        return fail(msg='用户名已存在')

    email = await User.get_or_none(user_email=user_info.user_email)
    if email:
        return fail(msg='邮箱已存在')

    if user_info.password != user_info.confirmPassword:
        return fail(msg='两次密码不一致')

    host = await User.get_or_none(client_host=request.client.host)
    if host:
        return fail(msg='你已注册')

    user_code = await User.get_or_none(share_code=user_info.code)
    if user_info.code:
        if user_code != user_code.code:
            return fail(msg='邀请码无效,请确认后再试！')

        print(user_info.code, 'share_code')
        last_four_chars = user_info.code[-5:]
        share_code = await request.app.state.cache.get(last_four_chars)

        user_info.password = en_password(user_info.password)
        user_info.client_host = request.client.host

        user_obj = await User.create(**user_info.dict())
        await request.app.state.cache.delete(last_four_chars)
        uses = await Userposts.get_or_none(code=user_info.code)
        if uses:
            uses.is_order = 1
            await uses.save()
        access_token = create_access_token({
            "username": user_obj.username,
            "user_email": user_obj.user_email,
            "client_host": user_obj.client_host,
            'id': user_obj.id,
        })
        await write_access_log(request, user_obj.id, '注册成功')
        user_info_without_excluded_fields = {
            'id': user_obj.id,
            "username": user_obj.username,
            "user_email": user_obj.user_email,
            'bio': user_obj.bio,
            'avatar': user_obj.avatar,
            'level': user_obj.level,
            'integral': user_obj.integral,
            'share_code': user_obj.share_code,
        }

        return success(data={'access_token': access_token, 'user_info': user_info_without_excluded_fields})

    user_info.password = en_password(user_info.password)
    user_info.client_host = request.client.host
    user_obj = await User.create(**user_info.dict())
    access_token = create_access_token({
        "username": user_obj.username,
        "user_email": user_obj.user_email,
        "client_host": user_obj.client_host,
        'id': user_obj.id,
    })
    await write_access_log(request, user_obj.id, '注册成功')
    user_info_without_excluded_fields = {
        'id': user_obj.id,
        "username": user_obj.username,
        "user_email": user_obj.user_email,
        'bio': user_obj.bio,
        'avatar': user_obj.avatar,
        'level': user_obj.level,
        'integral': user_obj.integral,
    }

    return success(data={'access_token': access_token, 'user_info': user_info_without_excluded_fields})


@router.post('/integral')
async def integral(request: Request):
    headers = request.headers.get("us")

    decoded_data = decode_access_token(headers)
    if decoded_data is None:
        return fail(msg='用户信息错误,请重新登录！')

    user = await User.get(id=decoded_data['id'])
    if user.username != decoded_data['username']:
        return fail(msg='用户信息错误')

    # 获取当前时间并设置时区
    current_time = datetime.now()
    last_integral_time = user.integral_time.replace(tzinfo=None)
    print(current_time, last_integral_time)
    # 将 user.integral_time 转换为 datetime 对象

    # 判断是否过了一天
    if current_time - last_integral_time >= timedelta(days=1):
        user.integral += 16
        user.integral_time = current_time
        await user.save()
        return success(data=user.integral, msg='积分更新成功')
    else:
        return fail(msg=f'积分更新时间未到,上次更新时间为{last_integral_time}')


@router.get('/pay/')
async def integral(request: Request,
                   pid: int = Query(..., description="Product ID"),
                   trade_no: str = Query(..., description="Trade Number"),
                   out_trade_no: str = Query(..., description="External Trade Number"),
                   type: str = Query(..., description="Payment Type"),
                   name: str = Query(..., description="Product Name"),
                   money: float = Query(..., description="Amount"),
                   trade_status: str = Query(..., description="Trade Status"),
                   sign: str = Query(..., description="Signature"),
                   sign_type: str = Query(..., description="Signature Type")):
    time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print(out_trade_no, pid, trade_no, type, name, money, trade_status, sign, sign_type, '1111111')
    trade = await request.app.state.cache.get(out_trade_no)
    print(trade)
    if trade is None:
        return fail(msg='订单不存在')
    trade_data = json.loads(trade)
    user = await User.get_or_none(id=trade_data['user'])
    if user is None:
        return fail(msg='用户不存在')
    post = await Post.get_or_none(id=trade_data['posts'])

    await Userposts.create(price=money,
                           time=time, is_order=1,
                           user=user,
                           posts=post,
                           order_link=trade_data['order_link'], )
    data = {"payurl": f"http://127.0.0.1:8888/detail/{post.id}", }
    return success(data=data, msg='支付成功', code=1)


@router.post('/order')
async def user_orders(request: Request):


    orders = await Order.all().values('order_price','id','order_name')
    # 转换为列表
    order_data = [order for order in orders]  # 提取 order_price

    print(order_data)
    return success(data=order_data, msg='获取成功', code=0)

@router.post('/orderpay')
async def integral(request: Request,item: dict = Body(...)):
    headers = request.headers.get("us")
    decoded_data = decode_access_token(headers)
    if decoded_data is None:
        return fail(msg='用户信息错误,请检查是否已登录！')
    user = await User.get_or_none(id=decoded_data['id'])

    print(user, 'user', )
    if user is None:
        return fail(msg='用户信息错误')
    id = item.get("id")

    menoy = await Order.get(id=id)
    user_vip = await User_vip.get_or_none(user=user)
    print(menoy.order_name, menoy.order_price, 'order')
    pid=f'https://ylxue.top/oredr/{menoy.id}'

    order = await process_payment_request(menoy.order_name, menoy.order_price, user.client_host, pid=pid)
    # print(order)
    redis_order={
        "user": user.id,
        "order": menoy.id,
        "order_link": order['order_no'],
    }
    await request.app.state.cache.set(order['order_no'], json.dumps(redis_order, default=str),ex=300)
    return success(data=order)